using System;
using System.Collections.Generic;
using System.Data;
using CardGameObject.CollectScene;
using Common;
using Entity;
using Mapper;
using UnityEngine;

namespace CardGameObject.UnpackScene
{
    public class UnpackManager : MonoBehaviour
    {
        public GameObject ScrollContent;
        public GameObject PackagePrefab;
        public GameObject CardPrefab;
        
        // 卡包列表
        private Dictionary<long, int> packageList = new();
        // 卡包对象列表
        private Dictionary<long, GameObject> packageObjectList = new();
        
        // 卡牌列表
        private List<GameObject> cardList = new List<GameObject>();
        
        // 缓存所有的卡牌
        private List<Card> allCards = null;

        private const int CARD_POSITION_NUM = 5;
        // 存储展示卡牌的位置
        private List<GameObject> cardPositons = new();
        
        private static UnpackManager instance;

        private void Awake()
        {
            instance = this;
        }

        public static UnpackManager GetInstance()
        {
            return instance;
        }

        private void Start()
        {
            for (int i = 1; i <= CARD_POSITION_NUM; i++)
            {
                GameObject playerPosition = GameObject.Find("CardPosition_" + i);
                cardPositons.Add(playerPosition);
            }            
            // 获取卡组ID
            PackageMapper packageMapper = new PackageMapper();
            // TODO 修改为当前登录的用户
            List<UserPackageVO> packages = packageMapper.ListPackagesByUserId(1);
            // 展示卡组内容
            // TODO 优化为每个卡包单独展示，而不是叠放展示
            foreach (UserPackageVO package in packages)
            {
                GameObject packageObject = Instantiate(PackagePrefab, ScrollContent.transform);
                packageObject.transform.parent = ScrollContent.transform;
                UnpackPackage unpackPackage = packageObject.GetComponent<UnpackPackage>();
                // 设置卡牌信息
                unpackPackage.SetPackageInfo(package.Id ,  package.Name , package.CardCount , package.PackageCount);
                packageList.Add(package.Id, package.PackageCount);
                packageObjectList.Add(package.Id, packageObject);
            }
            packageMapper.CloseConnection();
            
            // 缓存所有的卡牌
            CardMapper cardMapper = new CardMapper();
            allCards = cardMapper.ListAllCards();
        }

        /// <summary>
        /// 获取指定卡包的指定数量的随机卡牌，考虑稀有度概率
        /// </summary>
        /// <param name="packageId">卡包ID</param>
        /// <param name="count">获取的卡牌数量</param>
        /// <returns></returns>
        private List<Card> GetRandomCardByPackageId(int packageId, int count)
        {
            List<Card> result = new List<Card>();
            if (allCards == null)
            {
                Debug.LogError("所有卡牌数据未缓存，请先确保在 Start 方法中正确获取数据。");
                return result;
            }

            // 筛选出属于指定卡包的卡牌列表
            List<Card> cardsInPackage = new List<Card>();
            foreach (Card card in allCards)
            {
                if (card.PackageId == packageId)
                {
                    cardsInPackage.Add(card);
                }
            }

            if (cardsInPackage.Count == 0)
            {
                Debug.LogWarning($"卡包 {packageId} 中没有可用的卡牌。");
                return result;
            }

            System.Random random = new System.Random();

            // 确保至少有一张 R 或以上的卡
            bool hasROrAbove = false;
            for (int i = 0; i < count; i++)
            {
                Card selectedCard;
                if (!hasROrAbove && i == count - 1)
                {
                    // 如果前面都没抽到 R 或以上的卡，最后一张强制为 R 或以上
                    selectedCard = GetCardByRarity(cardsInPackage, random, new List<CardRarityEnum> { CardRarityEnum.UR, CardRarityEnum.SR, CardRarityEnum.R });
                    hasROrAbove = true;
                }
                else
                {
                    float randValue = (float)random.NextDouble();
                    if (randValue < 0.1f)
                    {
                        selectedCard = GetCardByRarity(cardsInPackage, random, new List<CardRarityEnum> { CardRarityEnum.UR });
                        hasROrAbove = true;
                    }
                    else if (randValue < 0.3f)
                    {
                        selectedCard = GetCardByRarity(cardsInPackage, random, new List<CardRarityEnum> { CardRarityEnum.SR });
                        hasROrAbove = true;
                    }
                    else if (randValue < 0.6f)
                    {
                        selectedCard = GetCardByRarity(cardsInPackage, random, new List<CardRarityEnum> { CardRarityEnum.R });
                        hasROrAbove = true;
                    }
                    else
                    {
                        selectedCard = GetCardByRarity(cardsInPackage, random, new List<CardRarityEnum> { CardRarityEnum.N });
                    }
                }

                if (selectedCard != null)
                {
                    result.Add(selectedCard);
                }
            }

            return result;
        }

        private Card GetCardByRarity(List<Card> cards, System.Random random, List<CardRarityEnum> rarities)
        {
            List<Card> filteredCards = new List<Card>();
            foreach (Card card in cards)
            {
                if (rarities.Contains((CardRarityEnum)card.CardRarity))
                {
                    filteredCards.Add(card);
                }
            }

            if (filteredCards.Count == 0)
            {
                return null;
            }

            int randomIndex = random.Next(0, filteredCards.Count);
            return filteredCards[randomIndex];
        }
        
        private GameObject CreateCardOnPosition(GameObject position)
        {
            Transform positionTransform = position.transform;
            Vector3 positionPosition = positionTransform.position;
            GameObject card = Instantiate(CardPrefab, positionPosition, CardPrefab.transform.rotation);
            return card;
        }

        public void UnpackPackage(int packageId, int cardCount)
        {
            // 删除当前展示的所有卡牌
            foreach (GameObject cardObject in cardList)
            {
                Destroy(cardObject);
            }
            cardList.Clear();
            // 删除玩家拥有的卡包
            PackageMapper packageMapper = new PackageMapper();
            // 判断玩家是否有剩余的该卡包
            List<UserPackageVO> userPackages = packageMapper.GetPackageByUserIdAndPackageId(1 , packageId);
            if (userPackages != null && userPackages.Count > 0 && userPackages[0].PackageCount>0)
            {
                packageMapper.UpdateUserPackageRelDataByPackageIdAndUserId(packageId, 1, userPackages[0].PackageCount-1);
            }
            else
            {
                packageMapper.DeleteUserPackageRelDataByPackageIdAndUserId(packageId, 1);
            }
            List<Card> cards = GetRandomCardByPackageId(packageId, cardCount);
            CardMapper cardMapper = new CardMapper();
            for (var i = 0; i < cards.Count; i++)
            {
                GameObject cardObject = CreateCardOnPosition(cardPositons[i]);
                cardObject.GetComponent<UnpackCard>().SetCardInfo(cards[i]);
                // 将抽到的卡牌加入到玩家背包中
                // 判断玩家是否含有该卡牌
                CollectCardVO card = cardMapper.GetCollectCardVOByCardIdAndUserId(cards[i].CardId, 1);
                if (card != null)
                {
                    cardMapper.UpdateUserCardCount(card.CardId , 1 , card.CardCount+1);
                }
                else
                {
                    cardMapper.AddCardToUser(cards[i].CardId, 1 , 1);
                }
                cardList.Add(cardObject);
            }
        }
    }
}